package com.example.demo.service;


import com.example.demo.domain.Category;
import com.example.demo.domain.CategoryExample;
import com.example.demo.mapper.CategoryMapper;
import com.example.demo.req.CategoryQueryReq;
import com.example.demo.req.CategorySaveReq;
import com.example.demo.resp.CategoryQueryResp;
import com.example.demo.resp.PageResp;
import com.example.demo.util.CopyUtil;
import com.example.demo.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.util.ObjectUtils;

import java.util.List;
@Service
public class CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private SnowFlake snowFlake;
    public PageResp<CategoryQueryResp> list(CategoryQueryReq req) {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        CategoryExample.Criteria criteria = categoryExample.createCriteria();

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
/*
        List<categoryResp> respList = new ArrayList<>();
        for (category category : categoryList) {
            //categoryResp categoryResp = new categoryResp();
            //categoryResp.setID(category.getId());
            //BeanUtils.copyProperties(category,categoryResp);
            categoryResp categoryResp = CopyUtil.copy(category, categoryResp.class);
            respList.add(categoryResp);
        }
 */
        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        PageResp<CategoryQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }
    public List<CategoryQueryResp> all(){
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);
        return list;
    }
    public void save(CategorySaveReq req){
        Category category = CopyUtil.copy(req,Category.class);
        if (ObjectUtils.isEmpty(req.getId())){
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        }else {
            categoryMapper.updateByPrimaryKey(category);
        }
    }
    public void delete(long id){
        categoryMapper.deleteByPrimaryKey(id);
    }
}